<?php

namespace aliyunoss;

use OSS\OssClient;
use Illuminate\Support\Str;

class AliyunOSS
{
    protected $ossClient;
    protected $bucket;
    protected $endpoint;
    protected $accessId;
    protected $accessKey;

    public function __construct()
    {
        $this->accessId = config('aliyun.oss.accessKey');
        $this->accessKey = config('aliyun.oss.secretKey');
        $this->endPubicPoint = config('aliyun.oss.endPubicPoint');
        $this->endpoint = config('aliyun.oss.endPoint');
        $this->bucket = config('aliyun.oss.bucket');
        $this->cdndomain = config('aliyun.oss.cdnDomain');
        
        $this->ossClient = new OssClient($this->accessId, $this->accessKey, $this->endPubicPoint);
    }

    public function upload($filePath, $objectKey = null)
    {
        if (!$objectKey) {
            $objectKey = Str::uuid() . '/' . basename($filePath);
        }

        try {
            $this->ossClient->putObject($this->bucket, $objectKey, file_get_contents($filePath));
            return env('OSS_CDN_DOMAIN') . '/' . $objectKey;
        } catch (OssException $e) {
            throw new \Exception($e->getMessage());
        }
    }

    public function url($objectKey)
    {
        return $this->ossClient->signUrl($this->bucket, $objectKey, 3600);
    }
}